class Solution {
public:
    struct Compare
    {
        bool operator()(const pair<string, int>& a, const pair<string, int>& b)
        {
            return a.second > b.second || (a.second == b.second && a.first < b.first);  //必须整个字符串比较，只比较first[0]不行，如果两个字符串开头都是a呢？
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        
        map<string, int> countMap;
        for(auto& e : words)
        {
            countMap[e]++;
        }
        vector<pair<string, int>> ret(countMap.begin(), countMap.end());
        sort(ret.begin(), ret.end(), Compare());
        vector<string> ans(k);
        for(int i = 0; i < k; i++)
        {
            ans[i] = ret[i].first;
        }
        return ans;
    }
};
